package com.laiyima.zhongjiang.linghuilv.demo.home;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.laiyima.zhongjiang.linghuilv.demo.R;
import com.laiyima.zhongjiang.linghuilv.demo.adapter.IncomListAdapter;
import com.laiyima.zhongjiang.linghuilv.demo.bean.IncomeBean;
import com.laiyima.zhongjiang.linghuilv.demo.util.TimeUtils;
import com.laiyima.zhongjiang.linghuilv.demo.view.IDShadowPopupView;
import com.laiyima.zhongjiang.linghuilv.demo.view.ListViewPlus;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.SimpleCallback;

import org.json.JSONArray;
import org.json.JSONObject;
import org.wangchenlong.datescroller.widget.DateScrollerDialog;
import org.wangchenlong.datescroller.widget.data.Type;
import org.wangchenlong.datescroller.widget.listener.OnDateSetListener;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import me.imid.swipebacklayout.lib.app.SwipeBackActivity;

public class IncomeDetailsActivity extends SwipeBackActivity implements View.OnClickListener,ListViewPlus.ListViewPlusListener {
    private String TAG="IncomeDetailsActivity";
    private int IncomeCode ,m,n;
    Calendar calendar= Calendar.getInstance(Locale.CHINA);
    private LinearLayout imageView,shouru_findby_time;
    private ListViewPlus mListView;
    private IncomeBean mIncomeBean;
    private IncomListAdapter mIncomListAdapter;
    private List<IncomeBean> ListIncomeBean = new ArrayList<>();
    private TextView show_monery,findby_t;
     private LinearLayout linearLayout;
    private int count,page_index,page_count;
    private static final long HUNDRED_YEARS = 100L * 365 * 1000 * 60 * 60 * 24L;
    protected TextView btnYearMonthDay;
    protected TextView tvTime;
    protected RelativeLayout activityMain;
    private String text="";
    private TextView mTvTime;
    private String type;
    private int cb=1;
    private IDShadowPopupView popupView;
    private SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM", Locale.ENGLISH);
    /**
     * 上次设置的时间
     */
    private long mLastTime = System.currentTimeMillis();

    /**
     * 数据的回调
     */
    private OnDateSetListener mOnDateSetListener = new OnDateSetListener() {
        @Override
        public void onDateSet(DateScrollerDialog timePickerView, long milliseconds) {
            mLastTime = milliseconds;
            text = getDateToString(milliseconds);
           // findby_t.setText(text);
            ListIncomeBean.clear();
            findView(text);
        }
    };





    @Override
    public void onRefresh() {
        ListIncomeBean.clear();
        intView();
             mIncomListAdapter.notifyDataSetChanged();
             loadData(ListViewPlus.REFRESH);
             // Log.e(TAG, "onRefresh:");


    }

    @Override
    public void onLoadMore() {
            if (page_index < page_count) {
                loadData(ListViewPlus.LOAD);
            } else {
                Toast.makeText(getBaseContext().getApplicationContext(), "已全部加载", Toast.LENGTH_SHORT).show();
                onLoadComplete();
            }
    }

    private void loadData(final int what) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message msg = handler.obtainMessage();
                msg.what = what;
                handler.sendMessage(msg);
            }
        }).start();
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ListViewPlus.REFRESH:
                    Log.e(TAG, "onRefresh:");
                    onLoadComplete();
                    Toast.makeText(getBaseContext().getApplicationContext(), "已刷新数据", Toast.LENGTH_SHORT).show();
                    break;
                case ListViewPlus.LOAD:
                    page_index++;
                    Toast.makeText(getBaseContext().getApplicationContext(), "已加载数据", Toast.LENGTH_SHORT).show();
                    Log.e(TAG, "onLoadMore:");
                    loadMode(page_index,text,type);
                    break;
            }
        };
    };

    private void onLoadComplete() {
        mListView.stopRefresh();
        mListView.stopLoadMore();
        mListView.setRefreshTime(TimeUtils.getCurrentTime());
    }
    protected boolean useThemestatusBarColor = false;//是否使用特殊的标题栏背景颜色，android5.0以上可以设置状态栏背景色，如果不使用则使用透明色值
    protected void setStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0及以上
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            //根据上面设置是否对状态栏单独设置颜色
            if (useThemestatusBarColor) {
                 //getWindow().setStatusBarColor(getResources().getColor(R.color.gray));
            } else {
                getWindow().setStatusBarColor(Color.TRANSPARENT);
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ) {//android6.0以后可以对状态栏文字颜色和图标进行修改
            getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN|View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_income_details);
        imageView= (LinearLayout) findViewById(R.id.incom_back);
        imageView.setOnClickListener(this);
        mListView= (ListViewPlus) findViewById(R.id.incom_list);
        mListView.setRefreshEnable(true);
        mListView.setLoadEnable(true);
        mListView.setAutoLoadEnable(true);
        mListView.setRefreshTime(TimeUtils.getCurrentTime());
        mListView.setListViewPlusListener(this);
        shouru_findby_time= (LinearLayout) findViewById(R.id.shouru_findby_time);
        shouru_findby_time.setOnClickListener(this);

        linearLayout= (LinearLayout) findViewById(R.id.show_list_income);
        findby_t= (TextView) findViewById(R.id.income_find_text);
    //    show_monery=findViewById(R.id.incom_monery);
        findby_t.setOnClickListener(this);

        setStatusBar();
//        int i=ListIncomeBean.size();
//        if(i==0){
//            linearLayout.setVisibility(View.VISIBLE);
//        }else {
//            linearLayout.setVisibility(View.GONE);
//        }

        intView();

    }

    @Override
    protected void onResume() {
        super.onResume();
    }
    @Override
    public void onClick(View v) {
        int id=v.getId();
        switch (id){
            case R.id.incom_back:
                finish();
                break;
            case R.id.shouru_findby_time:
                shoewtime();
                break;
            case R.id.income_find_text:
                showPartShadow(v);
                break;
        }
    }
    private void showPartShadow(final View v){
        if(popupView==null){
            popupView = (IDShadowPopupView) new XPopup.Builder(this)
                    .atView(v)
                    .setPopupCallback(new SimpleCallback() {
                        @Override
                        public void onShow() {
                            findby_t.setText("完成");
                        }
                        @Override
                        public void onDismiss() {
                            findby_t.setText("查询");
                            SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
                            int  t = sharedPreferences.getInt("income_type", 0);
                            if (t==0){
                                type="";
                                findTypt("");
                            }else if(t==1){
                                type="积分返现";
                                findTypt(type);
                            }else if(t==2){
                                type="服务商收益";
                                findTypt(type);
                            }else if (t==3){
                                type="推广收益";
                                findTypt(type);
                            }
                            else if (t==4){
                                type="积分兑换";
                                findTypt(type);
                            }
                        }
                    })
                    .asCustom(new IDShadowPopupView(this));
        }

        popupView.show();
    }

    private void findTypt(String type) {
        ListIncomeBean.clear();
        SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/api/Wallet/wallet_list");
        //需要带入的参数
        params.addBodyParameter("uid",  userID);
        params.addBodyParameter("page_size",  10);
        params.addBodyParameter("time",  text);
        params.addBodyParameter("type",  type);
        // params.addBodyParameter("captcha", captcha);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    IncomeCode = jsonObject.optInt("code", 0);
                    String data = jsonObject.optString("data", null);
                    if (!TextUtils.isEmpty(data)){
                        JSONObject jsonObjec = new JSONObject(data);
                        count= jsonObjec.optInt("count", 0);
                        page_count= jsonObjec.optInt("page_count", 0);
                        page_index= jsonObjec.optInt("page_index", 0);
                        Log.e(TAG, "count:"+count+"  page_count:"+page_count+"  page_index:"+page_index );
                    }
                    JSONObject jData = new JSONObject(data);
                    JSONArray list = jData.getJSONArray("list");
                    for (int i = 0; i < list.length(); i++) {
                        JSONObject value = list.getJSONObject(i);
                        String id = value.getString("id");
                        String uid = value.getString("uid");
                        String create_time = value.getString("create_time");
                        String wtype = value.getString("wtype");
                        String describe = value.getString("describe");
                        String money = value.getString("money");
                        String remark = value.getString("remark");
                        String admin_name = value.getString("admin_name");
                        mIncomeBean = new IncomeBean(id,uid,create_time,wtype,describe,money,remark,admin_name);
                        ListIncomeBean.add(mIncomeBean);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                Log.e(TAG, "回调成功" + result);
                if (IncomeCode == 200) {
                    mIncomListAdapter = new IncomListAdapter(getBaseContext().getApplicationContext(),ListIncomeBean);
                    mListView.setAdapter(mIncomListAdapter);
                }
                if (IncomeCode == 201) {
                }
                if (IncomeCode == 500) {
                    Toast.makeText(getBaseContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                    Log.e(TAG, "系统异常");
                }else{
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e(TAG, "回调失败");
            }
            @Override
            public void onCancelled(CancelledException cex) {

            }
            @Override
            public void onFinished() {
                if (ListIncomeBean.size()==0){
                    linearLayout.setVisibility(View.VISIBLE);
                }else {
                    linearLayout.setVisibility(View.GONE);
                }
            }
        });

    }



    private void shoewtime() {
                DateScrollerDialog dialog = new DateScrollerDialog.Builder()
                .setType(Type.YEAR_MONTH)
                .setMinMilliseconds(System.currentTimeMillis() - HUNDRED_YEARS)
                .setMaxMilliseconds(System.currentTimeMillis())
                .setCurMilliseconds(mLastTime)
                .setCallback(mOnDateSetListener)
                .build();


        if (dialog != null) {
            if (!dialog.isAdded()) {
                dialog.show(getFragmentManager(), "year_month_day");
            }
        }


       }
    public String getDateToString(long time) {
        Date d = new Date(time);
        return sf.format(d);
    }

    private void  loadMode(int page_index,String text,String type){
        SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/api/Wallet/wallet_list");
        //需要带入的参数
        params.addBodyParameter("uid",  userID);
        params.addBodyParameter("time",  text);
        params.addBodyParameter("page_index",  page_index);
        params.addBodyParameter("page_size",  10);
        params.addBodyParameter("type",  type);


        // params.addBodyParameter("captcha", captcha);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    IncomeCode = jsonObject.optInt("code", 0);
                    String data = jsonObject.optString("data", null);
                    JSONObject jData = new JSONObject(data);
                    JSONArray list = jData.getJSONArray("list");
                    for (int i = 0; i < list.length(); i++) {
                        JSONObject value = list.getJSONObject(i);
                        String id = value.getString("id");
                        String uid = value.getString("uid");
                        String create_time = value.getString("create_time");
                        String wtype = value.getString("wtype");
                        String describe = value.getString("describe");
                        String money = value.getString("money");
                        String remark = value.getString("remark");
                        String admin_name = value.getString("admin_name");
                        mIncomeBean = new IncomeBean(id,uid,create_time,wtype,describe,money,remark,admin_name);
                        ListIncomeBean.add(mIncomeBean);

                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }

                Log.e(TAG, "回调成功" + result);
                if (IncomeCode == 200) {
                    //mIncomListAdapter = new IncomListAdapter(getBaseContext().getApplicationContext(),ListIncomeBean);
                   // mListView.setAdapter(mIncomListAdapter);
                    mIncomListAdapter.notifyDataSetChanged();

                }
                if (IncomeCode == 201) {


                }
                if (IncomeCode == 500) {
                    Toast.makeText(getBaseContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                    Log.e(TAG, "系统异常");
                }else{


                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e(TAG, "回调失败");
            }
            @Override
            public void onCancelled(CancelledException cex) {

            }
            @Override
            public void onFinished() {

            }
        });

    }


    private void intView() {
        SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/api/Wallet/wallet_list");
        //需要带入的参数
        params.addBodyParameter("uid",  userID);
        params.addBodyParameter("page_size",  10);
        // params.addBodyParameter("captcha", captcha);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    IncomeCode = jsonObject.optInt("code", 0);
                    String data = jsonObject.optString("data", null);
                    if (!TextUtils.isEmpty(data)){
                        JSONObject jsonObjec = new JSONObject(data);
                           count= jsonObjec.optInt("count", 0);
                           page_count= jsonObjec.optInt("page_count", 0);
                           page_index= jsonObjec.optInt("page_index", 0);
                        Log.e(TAG, "count:"+count+"  page_count:"+page_count+"  page_index:"+page_index );
                    }
                    JSONObject jData = new JSONObject(data);
                    JSONArray list = jData.getJSONArray("list");
                    for (int i = 0; i < list.length(); i++) {
                        JSONObject value = list.getJSONObject(i);
                        String id = value.getString("id");
                        String uid = value.getString("uid");
                        String create_time = value.getString("create_time");
                        String wtype = value.getString("wtype");
                        String describe = value.getString("describe");
                        String money = value.getString("money");
                        String remark = value.getString("remark");
                        String admin_name = value.getString("admin_name");
                        mIncomeBean = new IncomeBean(id,uid,create_time,wtype,describe,money,remark,admin_name);
                        ListIncomeBean.add(mIncomeBean);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                Log.e(TAG, "回调成功" + result);
                if (IncomeCode == 200) {
                    mIncomListAdapter = new IncomListAdapter(getBaseContext().getApplicationContext(),ListIncomeBean);
                    mListView.setAdapter(mIncomListAdapter);
                }
                if (IncomeCode == 201) {
                }
                if (IncomeCode == 500) {
                    Toast.makeText(getBaseContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                    Log.e(TAG, "系统异常");
                }else{
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e(TAG, "回调失败");
            }
            @Override
            public void onCancelled(CancelledException cex) {

            }
            @Override
            public void onFinished() {
                 if (ListIncomeBean.size()==0){
                     linearLayout.setVisibility(View.VISIBLE);
                 }else {
                     linearLayout.setVisibility(View.GONE);
                 }
            }
        });

    }
    private void findView(String text) {
        SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/api/Wallet/wallet_list");
        //需要带入的参数
        params.addBodyParameter("uid",  userID);
        params.addBodyParameter("page_index", page_index);
        params.addBodyParameter("page_size", 10);
        params.addBodyParameter("time", text);

        // params.addBodyParameter("captcha", captcha);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    IncomeCode = jsonObject.optInt("code", 0);
                    String data = jsonObject.optString("data", null);
                    if (!TextUtils.isEmpty(data)){
                        JSONObject jsonObjec = new JSONObject(data);
                        count= jsonObjec.optInt("count", 0);
                        page_count= jsonObjec.optInt("page_count", 0);
                        page_index= jsonObjec.optInt("page_index", 0);
                        Log.e(TAG, "count:"+count+"  page_count:"+page_count+"  page_index:"+page_index );
                    }
                    JSONObject jData = new JSONObject(data);
                    JSONArray list = jData.getJSONArray("list");
                    for (int i = 0; i < list.length(); i++) {
                        JSONObject value = list.getJSONObject(i);
                        String id = value.getString("id");
                        String uid = value.getString("uid");
                        String create_time = value.getString("create_time");
                        String wtype = value.getString("wtype");
                        String describe = value.getString("describe");
                        String money = value.getString("money");
                        String remark = value.getString("remark");
                        String admin_name = value.getString("admin_name");
                        mIncomeBean = new IncomeBean(id,uid,create_time,wtype,describe,money,remark,admin_name);
                        ListIncomeBean.add(mIncomeBean);

                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }

                Log.e(TAG, "回调成功" + result);
                if (IncomeCode == 200) {
                    mIncomListAdapter = new IncomListAdapter(getBaseContext().getApplicationContext(),ListIncomeBean);
                    mIncomListAdapter.notifyDataSetChanged();
                    mListView.setAdapter(mIncomListAdapter);
                }
                if (IncomeCode == 201) {


                }
                if (IncomeCode == 500) {
                    Toast.makeText(getBaseContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                    Log.e(TAG, "系统异常");
                }else{


                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e(TAG, "回调失败");
            }
            @Override
            public void onCancelled(CancelledException cex) {

            }
            @Override
            public void onFinished() {
                if (ListIncomeBean.size()==0){
                    linearLayout.setVisibility(View.VISIBLE);
                }else {
                    linearLayout.setVisibility(View.GONE);
                }
            }
        });

    }
}
